package com.qufadai.mvc.context;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.qufadai.mvc.log.LogFactory;
import com.qufadai.mvc.log.Logger;
import com.qufadai.mvc.util.ClassUtil;
import com.qufadai.mvc.util.MethodUtil;

public class ContextHolder {

	private static Logger log = LogFactory.getDefaultLog();

	private static ThreadLocal<ContextHolder> localThis = new ThreadLocal<ContextHolder>();

	private HttpServletRequest request;

	private HttpServletResponse response;

	private ContextHolder() {
	}

	/**
	 * 获取上下文保持器
	 * 
	 * @return
	 */
	public static ContextHolder findInstance() {
		ContextHolder result = localThis.get();
		if (result == null) {
			result = new ContextHolder();
			localThis.set(result);
		}
		return result;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public static HttpSession getCurSession() {
		return findInstance().getRequest().getSession();
	}

	/**
	 * 向request中写入信息
	 * 
	 * @param key
	 * @param value
	 */
	public void setReqeustAttr(String key, Object value) {
		getRequest().setAttribute(key, value);
	}

	/**
	 * 向当前线程的request中注入相应的对象的方法
	 * 
	 * @param key
	 * @param value
	 */
	public static void setRequestAttribute(String key, Object value) {
		ContextHolder holder = findInstance();
		holder.getRequest().setAttribute(key, value);
	}

	/**
	 * 将最终的结果分发给相应的jsp的方法
	 * 
	 * @param url
	 */
	public void dispatcherUrl(String url) {
		RequestDispatcher dispatcher = getRequest().getRequestDispatcher(url);
		try {
			dispatcher.forward(getRequest(), getResponse());
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 使用response进行分发的方法
	 * 
	 * @param url
	 */
	public void dispatcherResponse(String url) {
		try {
			getResponse().sendRedirect(url);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getRequestUrl() {
		String result = getRequest().getRequestURI();
		System.out.println("result:" + result);
		System.out.println("contextUri:" + this.getContextUri());
		System.out.println("contextUri.len:" + this.getContextUri().length());
		if (result.indexOf(".") > -1) {
			result = result.substring(getContextUri().length() + 1,
					result.indexOf("."));
		} else {
			result = result.substring(getContextUri().length() + 1);
		}
		System.out.println(result);
		log.log(" the url that request is : " + result);
		return result;
	}

	public String getContextUri() {
		return getRequest().getContextPath();
	}

	/**
	 * 从request对象中实例化出一个对象
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Object initFromTheRequest(Class cla) {
		Field[] fields = cla.getDeclaredFields();
		Object instance = ClassUtil.findInstance(cla.getName());
		HttpServletRequest request = ContextHolder.findInstance().getRequest();
		for (Field field : fields) {
			Object[] params = { request.getParameter(field.getName()) };
			if (params[0] == null) {
				continue;
			}
			String method = "set"
					+ field.getName().substring(0, 1).toUpperCase()
					+ field.getName().substring(1);
			MethodUtil.invoke(method, instance, params);
		}
		return instance;
	}

	/**
	 * 用于向request中获取parameter之后注入到Attributes中
	 * 
	 * @param paramName
	 */
	public static void reinitParameterToRequest(String paramName) {
		String param = findInstance().getRequest().getParameter(paramName);
		findInstance().setReqeustAttr(paramName, param);
	}

	/**
	 * 内部分发方法，将请求转接到某个jsp
	 * 
	 * @param jspUrl
	 */
	public static void forward(String jspUrl) {
		findInstance().dispatcherUrl(jspUrl);
	}

	/**
	 * 将请求进行转发
	 * 
	 * @param url
	 */
	public static void sendRedirect(String url) {
		findInstance().dispatcherResponse(url);
	}

	/**
	 * 用于辅助ajax的一个方法
	 * 
	 * @param content
	 */
	public static void response(String content) {
		HttpServletResponse response = findInstance().getResponse();
		try {
			PrintWriter out = response.getWriter();
			out.write(content);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
